package com.winchain.chainbill.bill.biz.receive.rx;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.feign.PubUserFeign;
import com.shell.framework.command.ChainBase;
import com.shell.framework.command.CommandContext;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.governor.modules.message.keyword.RcvPassKeyword;
import com.shell.governor.user.po.PubUser;
import com.winchain.chainbill.bill.base.po.CbRcv;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillEvent;
import com.winchain.chainbill.bill.biz.receive.cmd.BillRcvMsgCmd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillRcvMsgSubscriber extends OnErrorNotImplementedSubscriber<BillEvent<CbRcv>> {
	@Autowired
	private PubUserFeign userFeign;
	@Autowired
	private BillRcvMsgCmd billRcvMsgCmd;

	public void onApplicationEvent(BillEvent<CbRcv> t) {
		CbRec cbRec = t.getBill().getRec();
		CbRcv cbRcv = (CbRcv) t.getBill().getSource();
		Object o = t.getValue("level");
		if (o != null) {
			Integer level = Integer.valueOf(o.toString());
			if (level.intValue() == 0) {
				Object isNotNeedAprv = t.getValue("isNotNeedAprv");
				if ((isNotNeedAprv == null) || (!((Boolean) isNotNeedAprv).booleanValue())) {
					receiveSendMsg(cbRec, cbRcv);
				}
			} else {
				CommandContext<Bill<CbRcv>> context = new CommandContext();
				ChainBase<Bill<CbRcv>> crb = new ChainBase();
				context.setSource(t.getBill());
				crb.add(this.billRcvMsgCmd);
				crb.execute(context);
			}
		}
	}

	private void receiveSendMsg(CbRec cbRec, CbRcv cbRcv) {
		String template = "MT01302";
		RcvPassKeyword keyWord = new RcvPassKeyword();

		keyWord.setSellerNm(cbRcv.getSellerNm());
		keyWord.setSndDate(DateUtil.parseDate(cbRcv.getCreateTime(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
		keyWord.setBillAmt(String.valueOf(cbRec.getBillAmt()));
		keyWord.setUserName(CommonDataUtil.getUserName());
		keyWord.setUrl(SpringContextUtil.getProperty("chainbill.website"));

		PubUser pubUser = this.userFeign.selectByKey(CommonDataUtil.getUserId());
		keyWord.setPhoneNum(pubUser.getPhoneNo());

		String senderId = CommonDataUtil.getUserId();

		MessageSender.sendMessageByTmpl(senderId, template, keyWord, cbRec.getFinId());
		template = "MT02202";
		MessageSender.sendMessageByTmpl(senderId, template, keyWord, cbRec.getFinId());
	}
}
